package com.zhaoyue.study.concurrency.thread.daemon;

import java.util.Date;

import java.util.concurrent.LinkedBlockingDeque;


/**
 * Created with IntelliJ IDEA.
 * User: Administrator
 * Date: 2016/8/30
 * Time: 17:32
 * To change this template use File | Settings | File Templates.
 */
public class CleanTask extends Thread {

    private LinkedBlockingDeque<Event> queue;
    public CleanTask(LinkedBlockingDeque<Event> queue){
        this.queue = queue;
        setDaemon(true);
    }

    public void run() {

        while (true){
            Date date = new Date();
            clean(date);
        }
    }

    private void clean(Date date) {
        long difference = 0;
        boolean delete = false;

        if (queue.size() == 0) {
            return;
        }

        do {
            Event e = queue.getLast();
            difference = date.getTime() - e.getDate().getTime();
            if (difference > 10000) {
                System.out.printf("Cleaner: %s\n", e.getEvent());
                queue.removeLast();
                delete = true;
            }
        } while (difference > 10000);
        if (delete) {
            System.out.printf("Cleaner: Size of the queue: %d\n", queue.size());
        }
    }
}
